

public class MoveToFront
{
	// apply move-to-front encoding, reading from standard input and writing to standard output
    public static void encode()
    {
    	char[] sequence = new char[256];
    	int[] positions = new int[256];
    	for(char i = 0; i < 256; i++) {
    		positions[i] = i;
    		sequence[i]  = i;
    	}
    	
    	while(!BinaryStdIn.isEmpty())
    	{
    		char ch = BinaryStdIn.readChar();
    		int pos = positions[ch];
    		
    		BinaryStdOut.write((byte)pos);
    		
    		for(int i = pos; i > 0; i--) {
    			sequence[i] = sequence[i-1];
    			positions[ sequence[i-1] ]++;
    		}
    		sequence[0] = ch;
    		positions[ch] = 0;
    	}
    	BinaryStdOut.close();
    }

    // apply move-to-front decoding, reading from standard input and writing to standard output
    public static void decode()
    {
    	char[] positions = new char[256];
    	for(char i = 0; i < 256; i++)
    		positions[i] = i;
    	
    	while(!BinaryStdIn.isEmpty())
    	{
    		int  pos = (int)BinaryStdIn.readChar();
    		char ch  = positions[pos];
    		
    		BinaryStdOut.write(ch);
    		
    		for(int i = pos; i > 0; i--)
    			positions[i] = positions[i-1];
    		
    		positions[0] = ch;
    	}
    	BinaryStdOut.close();
    }

    // if args[0] is '-', apply move-to-front encoding
    // if args[0] is '+', apply move-to-front decoding
    public static void main(String[] args)
    {
    	if("-".equals(args[0]))
    		encode();
    	else
    		decode();
    }
}
